#ifndef A8_CURL_H
#define A8_CURL_H

#include <curl/curl.h>
#include <curl/easy.h>

namespace a8
{
	namespace http
	{
		static size_t _ReceiveResponse(void *buffer, size_t size, size_t nmemb, void *user_p)
		{
			std::string *respone = (std::string *)user_p;
			respone->append((char*)buffer, size * nmemb);
			return size * nmemb;
		}

		static bool Post(const std::string& url, const std::string& postdata,
                         std::string& response, int timeout=10)
		{
			CURL *curl = curl_easy_init();
			curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
			curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
			curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postdata.c_str());
			curl_easy_setopt(curl, CURLOPT_HTTPPOST, 1);
			curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &_ReceiveResponse);
			curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
			bool ok = curl_easy_perform(curl) == CURLE_OK;
			curl_easy_cleanup(curl);
			return ok;
		}

		static bool Get(const std::string& url, std::string& response, int timeout=10)
		{
			CURL *curl = curl_easy_init();
			curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
			curl_easy_setopt(curl, CURLOPT_URL, url.c_str());			
			curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
			curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &_ReceiveResponse);
			curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
			bool ok = curl_easy_perform(curl) == CURLE_OK;
			curl_easy_cleanup(curl);
			return ok;
		}
	}
}

#endif
